package com.example.ojdemo1.common;

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

/**
 * 负责文件的读写
 */
public class FileUtil {

    /**
     * 读取 filePath 文件的内容并返回
     * @param filePath
     * @return
     */
    public static String readFile(String filePath) {
        StringBuilder result = new StringBuilder();
        try (FileReader fileReader = new FileReader(filePath)) {
            while(true) {
                int read = fileReader.read(); //这里是将字符以 int 形式存储了
                if(read == -1) {
                    break;
                }
                result.append((char) read);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result.toString();
    }

    /**
     * 向 filePath 中写入 content
     * @param filePath
     * @param content
     */
    public static void writeFile(String filePath, String content) {
        try(FileWriter fileWriter = new FileWriter(filePath)) {
            fileWriter.write(content);
            fileWriter.flush(); //刷新缓冲区
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 测试
     * @param args
     */
    public static void main(String[] args) {
        writeFile("d:/aa.txt", "hello world!");
        String s = readFile("d:/aa.txt");
        System.out.println(s);
    }

}
